<template>
  <el-drawer
    :append-to-body="true"
    :wrapperClosable="globalDisabled"
    :title="title"
    size="1200px"
    :visible="open"
    @close="handleClose"
  >
    <div class="drawer_container">
      <div class="title_box">
        <ancestorsNameDeal class="index_name" :text="ancestorsName" :maxLength="!globalDisabled?45:90"></ancestorsNameDeal>
        <div class="top_btns" v-if="!globalDisabled">
          <div @click="addTopic" class="blue_btn">
            <svg-icon class-name="btn_icon" icon-class="add_svg"/>
            手动录入试题
          </div>
          <div @click="showTopicBank" class="orange_btn">
            <svg-icon class-name="btn_icon" icon-class="muttle_svg"/>
            从试题库选择
          </div>
          <el-dropdown>
            <div class="green_btn">
              <svg-icon class-name="btn_icon" icon-class="AI_svg"/>
              AI出题
            </div>
            <el-dropdown-menu slot="dropdown">
              <div @click="showAiTopic(1)">
                <el-dropdown-item>基于课程内容</el-dropdown-item>
              </div>
              <div @click="showAiTopic(0)">
                <el-dropdown-item>联网出题</el-dropdown-item>
              </div>
            </el-dropdown-menu>
          </el-dropdown>
          <div @click="multipleDel" class="danger_btn">
            <i class="el-icon-delete"></i>
            批量删除
          </div>
        </div>
      </div>
      <div class="mid">
        <el-table
          v-loading="tableLoading"
          height="calc(100vh - 200px)"
          :header-cell-style="tableHeaderStyle"
          :data="containerList"
          class="cum_table"
          @selection-change="handleSelectionChange"
        >
          <el-table-column v-if="!globalDisabled" width="55" type="selection" align="center"></el-table-column>
          <el-table-column label="序号" type="index" align="center"></el-table-column>
          <el-table-column label="题型" align="center" prop="topicType">
            <template slot-scope="scope">
              <el-tag>{{ $store.getters.topicTypeText[scope.row.topicType] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="题干" width="500" align="center" prop="content">
            <template slot-scope="scope">
              <div @click="getByEditor(3, scope.row.content)"
                :class="{content_html: $isIncludesHtml(scope.row.content) }"
                class="line_feed w_fixed overtxt"
              >
                {{ scope.row.content }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="难度" align="center" prop="difficulty">
            <template slot-scope="scope">
              <el-tag type="success">{{ $store.getters.difficultyText[scope.row.difficulty] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center" v-if="!globalDisabled">
            <template slot-scope="scope">
              <div class="icon_box">
                <i @click="editTopic(scope.row)" class="el-icon-edit color_hover pointer"></i>
                <i @click="delContainerTopic(scope.row.id)" class="el-icon-delete color_hover pointer"></i>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="btns" v-if="globalDisabled">
        <el-button @click="handleClose">关闭</el-button>
      </div>
      <!--  添加/编辑试题抽屉  -->
      <addTopicDrawer :index-id="indexId" @submit="saveTopicByType" :open.sync="showTopicState" :topic-id="currentTopicId"
                      :course-id="courseId" :open-type="openTopicType"
      ></addTopicDrawer>
      <!--  题库  -->
      <topicBankDrawer :examId="examId" @sumitData="importTopicByBank" title="从题库导入" :open.sync="showTopicBankDrawer" :enterType="2"
                       :course-id="courseId"
      ></topicBankDrawer>
      <!--  AI出题    -->
      <AIoutTopicDrawer :show.sync="showAiDrawer" @updateData="getContainerTopicList" :container-id="containerRow.id" :open-type="showAiType" :index-id="indexId" :course-id="courseId"></AIoutTopicDrawer>
      <!--  编辑弹窗  -->
      <editDrawer
        title="题干详情"
        :show.sync="showDrawer"
        :openType="propOpenType"
        :propEditorValue="propEditorValue"
      ></editDrawer>
    </div>
  </el-drawer>
</template>

<script>
import addTopicDrawer from './addTopicDrawer'
import topicBankDrawer from './topicBankDrawer'
import AIoutTopicDrawer from './AIoutTopicDrawer'
import editDrawer from "../../tea_course/components/editDrawer";
import ancestorsNameDeal from '../../../components/ancestorsNameDeal'
import {
  addContainerTopicApi,
  editTopicApi,
  removeContainerTopicApi,
  getContainerTopicListApi,
  addContainerTopicByBankApi
} from '@/api/ExaminationModule'
import { getAncestorsNameApi } from '@/api/course/course'

export default {
  name: 'editContainerDrawer',
  components: {
    topicBankDrawer,
    AIoutTopicDrawer,
    ancestorsNameDeal,
    editDrawer,
    addTopicDrawer,
  },
  props: {
    open: {
      type: Boolean,
      default: false
    },
    containerRow: {
      type: [Object],
      default: '',
      request: true
    },
    courseId: {
      type: [Number, String],
      default: ''
    },
    examId: {
      type: [Number, String],
      default: ''
    },
    indexId: {
      type: [Number, String],
      default: ''
    },
    globalDisabled: {
      type: [Boolean],
      default: false
    },
    title: {
      type: String,
      default: '编辑抽题容器'
    }
  },
  data() {
    return {
      // AI出题类型  0: "AI出题(联网出题)" 1: "AI出题(基于课程内容)",
      showAiType: 1,
      // AI出题抽屉状态
      showAiDrawer: false,
      showTopicBankDrawer: false,
      //添加/编辑试题抽屉状态
      showTopicState: false,
      //当前题目id
      currentTopicId: '',
      //试题抽屉打开类型
      openTopicType:'',
      ancestorsName:'',
      //富文本录入类型 1：添加 2：编辑 3：查看
      propOpenType: 1,
      //富文本录入抽屉状态
      showDrawer: false,
      //富文本录入组件---内容
      propEditorValue: "",
      tableLoading:false,
      containerList:[],
      containerIds:[],
      //表头样式
      tableHeaderStyle: {
        'background-color': '#f8f8f9',
        'color': '#333333',
        'font-size': '14px',
        'font-family': 'PingFangSC, PingFang SC',
        'font-weight': '400'
      }
    }
  },
  watch: {
    open(val) {
      if (val) {
        this.getAncestorsName()
        this.getContainerTopicList()
      }
    }
  },
  methods: {
    //富文本录入
    getByEditor(type, Value) {
      if (type == 3 && !this.$isIncludesHtml(Value)) {
        return;
      }
      this.propEditorValue = Value;
      this.propOpenType = type;
      this.showDrawer = true;
    },
    async getAncestorsName() {
      try {
        let res = await getAncestorsNameApi(this.indexId)
        const { code, msg } = res
        if (code == 200) {
          this.ancestorsName = msg
        }
      } catch (e) {
        console.error(e)
      }
    },
    showAiTopic(type) {
      this.showAiType = type
      this.showAiDrawer = true
    },
    //显示题库
    showTopicBank() {
      this.showTopicBankDrawer = true
    },
    // 题库导入试题
    async importTopicByBank(e) {
      let topicIds = e.join(',')
      const loading = this.$loading({
        lock: true,
        text: '正在处理...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      try {
        let res = await addContainerTopicByBankApi(this.containerRow.id, topicIds)
        const { code } = res
        if (code == 200) {
          this.$modal.msgSuccess('导入成功')
          this.getContainerTopicList()
        }
      } catch (e) {
        console.error(e)
      } finally {
        loading.close()
      }
    },
    //保存
    saveTopicByType(e) {
      if (this.openTopicType === 'add') {
        this.addContainerTopic(this.containerRow.id, e)
      } else {
        /**
         *  e.type==1 新增
         * e.type==2 保存并同步
         * e.type==3 保存并新增
         * */
        //保存并同步
        if (e.type == 2) {
          this.editConnmonTopic(e)
        }else {
          this.addContainerTopic(this.containerRow.id,e)
        }
      }
    },
    //添加题目
    async addContainerTopic(containerId, params) {
      const loading = this.$loading({
        lock: true,
        text: '正在添加...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      try {
        let res = await addContainerTopicApi(containerId, params)
        if (res.code == 200) {
          this.$modal.msgSuccess('添加成功')
          this.getContainerTopicList()
        }
      } catch (e) {
        console.error(e)
      } finally {
        loading.close()
      }
    },
    //修改题目
    async editConnmonTopic(params) {
      const loading = this.$loading({
        lock: true,
        text: '正在处理...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      try {
        let res = await editTopicApi(params)
        const { code } = res
        if (code == 200) {
          this.$modal.msgSuccess('编辑成功')
          this.getContainerTopicList()
        }
      } catch (e) {
        console.error(e)
      } finally {
        loading.close()
      }
    },
    //关闭抽屉
    handleClose() {
      this.$emit('update:open', false)
      if (!this.globalDisabled) {
        this.$emit('refresh', this.containerRow)
      }
    },
    //修改题目
    editTopic(row) {
      this.showTopicState = true
      this.currentTopicId = row.id
      this.openTopicType = 'edit'
    },
    //添加题目
    addTopic() {
      this.showTopicState = true
      this.openTopicType = 'add'
    },
    //批量删除
    multipleDel() {
      if (this.containerIds.length === 0) {
        this.$modal.msgWarning('请先选择要删除的题目')
        return
      }
      this.delContainerTopic(this.containerIds.join(','))
    },
    //选择题目
    handleSelectionChange(selection) {
      this.containerIds = selection.map((item) => item.id)
    },
    //获取抽题容器里的题目
    async getContainerTopicList() {
      this.tableLoading = true
      try {
        const res = await getContainerTopicListApi(this.containerRow.id)
        const { code, data } = res
        if (code == 200) {
          this.containerList = data
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.tableLoading = false
      }
    },
    //删除抽题容器里的小题(不会删除题库的题目)
    delContainerTopic(ids) {
      this.$confirm('删除后可从题库中再次选择题目加入试卷，是否确认删除？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const loading = this.$loading({
          lock: true,
          text: '正在删除...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        try {
          let res = await removeContainerTopicApi(this.containerRow.id, ids)
          const { code } = res
          if (code == 200) {
            this.$modal.msgSuccess('删除成功')
            this.getContainerTopicList()
          }
        } catch (e) {
          console.error(e)
        } finally {
          loading.close()
        }
      }).catch(() => {
        this.$modal.msgInfo('已取消')
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import "../../../assets/styles/mixin.scss";

.drawer_container {
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;

  .title_box {
    margin-top: 16px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .index_name {
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 500;
      font-size: 16px;
      color: #333333;
    }

    .top_btns {
      display: flex;
      align-items: center;
      gap: 0 16px;

      .blue_btn {
        @include plain_hover(#F3FAFF, #1677FF, #ffffff) {
          width: 130px;
          height: 32px;
          border-radius: 8px;
          border: 1px solid #1677FF;
          gap: 0 4px;
        }
      }

      .orange_btn {
        @include plain_hover(#FFF8EE, #E6A23B, #ffffff) {
          width: 130px;
          height: 32px;
          border-radius: 8px;
          border: 1px solid #E6A23B;
          gap: 0 4px;
        }
      }

      .green_btn {
        @include plain_hover(#ECFFFA, #28B28B, #ffffff) {
          width: 88px;
          height: 32px;
          border-radius: 8px;
          border: 1px solid #28B28B;
          gap: 0 4px;
        }
      }

      .danger_btn {
        @include plain_hover(#FFEEEE, #E95756, #ffffff) {
          width: 102px;
          height: 32px;
          border-radius: 8px;
          border: 1px solid #F99999;
          gap: 0 4px;
        }
      }
    }
  }

  .mid {
    margin-top: 20px;

    .cum_table {
      width: 100%;
      border-radius: 8px;
      border: 1px solid #E8EAEB;

      .icon_box {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 0 8px;
      }
    }

    ::v-deep .el-table:before {
      height: 0;
    }
  }

  .btns {
    width: 100%;
    padding: 10px 0;
    box-sizing: border-box;
    display: flex;
    justify-content: flex-end;
  }
}

.color_hover {
  &:hover {
    color: #28b28b;
  }
}
.w_fixed {
  width: 100%;
}
.content_html {
  position: relative;
  cursor: pointer;
  height: 100%;
  &:hover {
    user-select: none;
    &:after {
      content: "预览";
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
      color: #ffffff;
      background: rgba(0, 0, 0, 0.2);
    }
  }
}
</style>
